"""
测试二：沪深大盘数据API
提供大盘指数的实时数据和历史数据接口
"""

from fastapi import APIRouter, HTTPException
from typing import Dict, List, Optional
from ..services.market_index_service import market_service

router = APIRouter(prefix="/api/market", tags=["大盘数据"])

@router.get("/indices", summary="获取所有大盘指数实时数据")
async def get_all_indices():
    """获取所有大盘指数的实时数据"""
    try:
        data = await market_service.get_from_redis()
        return {
            "success": True,
            "data": data,
            "message": "获取大盘数据成功"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取大盘数据失败: {str(e)}")

@router.get("/indices/{code}", summary="获取单个指数实时数据")
async def get_index_data(code: str):
    """获取单个指数的实时数据"""
    try:
        data = await market_service.get_from_redis(code)
        if not data:
            raise HTTPException(status_code=404, detail=f"未找到指数 {code}")
            
        return {
            "success": True,
            "data": data,
            "message": f"获取 {code} 数据成功"
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取指数数据失败: {str(e)}")

@router.get("/history", summary="获取大盘历史数据")
async def get_market_history(days: int = 1):
    """获取大盘历史数据用于图表展示"""
    try:
        if days < 1 or days > 7:
            raise HTTPException(status_code=400, detail="天数范围应在1-7之间")
            
        history_data = await market_service.get_history_data(days)
        return {
            "success": True,
            "data": history_data,
            "count": len(history_data),
            "message": f"获取{days}天历史数据成功"
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取历史数据失败: {str(e)}")

@router.get("/chart/{code}", summary="获取指数图表数据")
async def get_index_chart(code: str, days: int = 1):
    """获取单个指数的图表数据"""
    try:
        if code not in market_service.market_indices:
            raise HTTPException(status_code=404, detail=f"不支持的指数代码: {code}")
            
        history_data = await market_service.get_history_data(days)
        
        # 提取指定指数的数据
        chart_data = []
        for record in history_data:
            if code in record.get("data", {}):
                index_data = record["data"][code]
                chart_data.append({
                    "timestamp": record["timestamp"],
                    "value": float(index_data.get("current", 0)),
                    "change_percent": float(index_data.get("change_percent", 0))
                })
        
        return {
            "success": True,
            "data": {
                "code": code,
                "name": market_service.market_indices[code],
                "chart_data": chart_data
            },
            "message": f"获取 {code} 图表数据成功"
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取图表数据失败: {str(e)}")

@router.post("/start", summary="启动大盘数据采集")
async def start_market_collection():
    """启动大盘数据采集任务"""
    try:
        await market_service.start_data_collection()
        return {
            "success": True,
            "message": "大盘数据采集已启动"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"启动采集失败: {str(e)}")

@router.post("/stop", summary="停止大盘数据采集")
async def stop_market_collection():
    """停止大盘数据采集任务"""
    try:
        await market_service.stop_data_collection()
        return {
            "success": True,
            "message": "大盘数据采集已停止"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"停止采集失败: {str(e)}")

@router.get("/status", summary="获取采集服务状态")
async def get_market_status():
    """获取大盘数据采集服务状态"""
    try:
        status = market_service.get_status()
        return {
            "success": True,
            "data": status,
            "message": "获取状态成功"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取状态失败: {str(e)}")

@router.get("/redis-test", summary="测试Redis连接")
async def test_redis():
    """测试Redis连接状态"""
    try:
        connected = await market_service.init_redis()
        return {
            "success": True,
            "redis_connected": connected,
            "message": "Redis连接测试完成"
        }
    except Exception as e:
        return {
            "success": False,
            "redis_connected": False,
            "message": f"Redis连接失败: {str(e)}"
        }
